﻿using log4net;
using Mangox.Model.MangoxDB;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Wen.Helpers.Common;

namespace Mangox.BLL.Mangox
{
    public class MgxCommBLL
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";
        private static string tokenkey = "m`G!x8^%";  //Token
        private const string startPwdKey = "mgx@888";  //UserPwd
        private const string endPwdKey = "888$mgx";

        /// <summary>
        /// Token密钥
        /// 可以+盐 +时间
        /// </summary>
        /// <returns></returns>
        public static string CreateToken(string userid, string userHash = null)
        {
            try
            {
                //return SecurityHelper.Md5Encrypt(userid + "mgx", Encoding.UTF8);

                //使用可解密方案，解密出用户id 和 时间
                var token = SecurityHelper.DesEncrypt($"{userid};{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")};{userHash};", tokenkey);
                token = HttpUtility.UrlEncode(token);
                return token;
            }
            catch (Exception ex)
            {
                log.Error(className + $"CreateToken Fail-{ex.ToString()}");
            }
            return null;
        }

        /// <summary>
        /// 验证解析Token
        /// </summary>
        /// <returns></returns>
        public static MgxToken DecryptToken(string token)
        {
            MgxToken tModel = null;
            try
            {
                token = HttpUtility.UrlDecode(token);
                //使用可解密方案，解密出用户id
                var tokenInfo = SecurityHelper.DesDecrypt(token, tokenkey);
                var arr = tokenInfo.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                int tuid = 0;
                if (arr != null && arr.Length > 1 && int.TryParse(arr[0],out tuid))
                {
                    tModel = new MgxToken();
                    tModel.IsToken = true;
                    tModel.UserID = tuid; //？需要验证数据库存在并启用的用户
                    tModel.CreateTokenTime = arr[1];
                    if (arr.Length > 2)
                    {
                        tModel.MgxHashID = arr[2];
                    }
                }
                else
                {
                    //非正常Token
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"解析Token异常 token-【{token}】，Fail-{ex.ToString()}");
            }
            return tModel;
        }


        /// <summary>
        /// 用户密码加密
        /// md5 +盐 + md5
        /// </summary>
        /// <returns></returns>
        public static string GetUserPwd(string pwd)
        {
            string retPwd = null;
            try
            {
                retPwd = SecurityHelper.Md5Encrypt(pwd, Encoding.UTF8);
                retPwd = SecurityHelper.Md5Encrypt(startPwdKey + retPwd + endPwdKey, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                log.Error(className + $"GetUserPwd Fail-{ex.ToString()}");
            }
            return retPwd;
        }


        public static string CheckPassword(string pwd)
        {
            if (string.IsNullOrWhiteSpace(pwd))
            {
                return "密码不能为空";
            }
            if (pwd.Length < 6)
            {
                return "密码不能小于6个字符";
            }
            if (pwd.Length > 18)
            {
                return "密码不能大于18个字符";
            }
            return null;
        }

        public static string CheckMgxHashID(string mgxHashID)
        {
            if (string.IsNullOrWhiteSpace(mgxHashID))
            {
                return "hash不能为空";

                //创建MGX账号Hash
                //p.MgxHashID = MangoxController.CreateMgxUser();
                //if (string.IsNullOrEmpty(p.MgxHashID) || p.MgxHashID.Length != 64)
                //{
                //    result.Msg = "创建hash失败";
                //    return result;
                //}
            }
            else if (mgxHashID.Length != 64)
            {
                return "hash格式不正确";
            }
            return null;
        }

        public static string CheckERCAddress(string ercAddress)
        {
            //if (string.IsNullOrWhiteSpace(ercAddress))
            //{
            //    return "hash不能为空";
            //}
            //else if (ercAddress.Length != 64)
            //{
            //    return "hash格式不正确";
            //}
            return null;
        }

    }
}
